/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useState } from 'react';
import { ChildProjectionCommandProps } from './types';

type FormData = {
  surface?: pickedFaceData;
  point?: pickedVertexData;
  vector?: pickedLineData | pickedFaceData;
};

type Params = {
  surface: string;
  point: string;
  vector: string;
};

export function PointProjection({
  onClose,
  props,
  editDxid,
}: ChildProjectionCommandProps) {
  const [formData, setFormData] = useState<FormData>({});

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({});
      return;
    }
    const params: Params = props.params;
    const { surface, point, vector } = params;

    await initEditDependency([surface, point, vector]);

    setFormData({
      surface: picker.generatePickObjByPickID(surface) as pickedFaceData,
      vector: picker.generatePickObjByPickID(vector) as
        | pickedLineData
        | pickedFaceData,
      point: picker.generatePickObjByPickID(point) as pickedVertexData,
    });
  }, [editDxid]);

  const isFormDataValid = () => {
    const { point, surface, vector } = formData;

    return point != null && surface != null && vector != null;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-point-projection', {
      commandName: 'CreateVertex',
      editDxid,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    const { point, surface, vector } = formData;

    return confirmCommand(
      {
        a: {
          mode: 'project',
          point: point.vertexId,
          surface: surface.meshId,
          vector: getIdOfPickedObj(vector),
        },
      },
      preview,
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      surface: {
        type: 'string',
        format: PickInputRJSFFormat.PickSurface,
      },
      point: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      vector: {
        type: 'string',
        format: PickInputRJSFFormat.PickDirection,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      onCancel={onClose}
      schema={schema}
      submitLoading={isLoading}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        surface: {
          'ui:placeholder': '请输入投影面',
          'ui:autofocus': true,
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
        point: {
          'ui:placeholder': '请输入点',
        },
        vector: {
          'ui:placeholder': '请输入方向（直线或平面）',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}
